package com.zshan.clinic.admin.service.config;

import com.fasterxml.jackson.core.type.TypeReference;
import com.zshan.clinic.admin.constant.Constants;
import com.zshan.clinic.admin.entity.dto.TemplateMedicalExamDTO;
import com.zshan.clinic.admin.entity.dto.TemplateMedicalFieldDTO;
import com.zshan.clinic.admin.entity.dto.TemplateMedicalRxDTO;
import com.zshan.clinic.admin.entity.medical.exam.ExamDetail;
import com.zshan.clinic.admin.entity.medical.field.MedicalFieldDetail;
import com.zshan.clinic.admin.entity.medical.rx.RxDrug;
import com.zshan.clinic.admin.entity.medical.rx.RxExt;
import com.zshan.clinic.admin.entity.medical.rx.RxInfusion;
import com.zshan.clinic.admin.entity.medical.rx.RxTcm;
import com.zshan.clinic.admin.entity.medical.rx.base.*;
import com.zshan.clinic.admin.entity.request.*;
import com.zshan.clinic.admin.entity.vo.*;
import com.zshan.clinic.admin.mapper.config.SpecTemplateMapper;
import com.zshan.clinic.admin.service.MedicalValidateService;
import com.zshan.clinic.admin.util.RxUtil;
import com.zshan.clinic.common.constant.CommonConstant;
import com.zshan.clinic.common.enums.*;
import com.zshan.clinic.common.exception.BusinessFailException;
import com.zshan.clinic.common.util.json.JsonUtil;
import com.zshan.clinic.common.util.string.StringUtil;
import com.zshan.clinic.common.util.validate.TagCheckUtil;
import com.zshan.clinic.database.dao.*;
import com.zshan.clinic.database.model.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 病历模板
 * @author lichen
 */
@Service
@Slf4j
public class TemplateService extends MedicalValidateService {

    /**
     * 模板组  感冒发烧组
     */
    @Autowired
    private TemplateGroupMapper templateGroupMapper;

    /**
     * 模板简要信息  普通感冒
     */
    @Autowired
    private TemplateInfoMapper templateInfoMapper;

    @Autowired
    private TemplateMedicalFieldMapper templateMedicalFieldMapper;

    @Autowired
    private TemplateMedicalExamMapper templateMedicalExamMapper;

    @Autowired
    private TemplateMedicalRxMapper templateMedicalRxMapper;


    @Autowired
    private SpecTemplateMapper specTemplateMapper;

    /**
     * 获取所有的组，用来分享时候选组
     * @param clinicId
     * @param empId
     * @param templateType
     * @return
     */
    public List<TemplateGroupSelectVo> getGroupSelectList(Long clinicId, Long empId, String templateCategory,String templateType){
        return specTemplateMapper.getGroupSelectList(clinicId,empId,templateCategory,templateType);
    }


    /**
     * 获取模板组列表，用于首次刷新
     * @param templateType
     * @return
     */
    public List<TemplateGroupVo> getTemplateGroupList(Long clinicId, String groupName, Long empId, String templateCategory,String templateType){
        return specTemplateMapper.getTemplateGroupList(clinicId,groupName,empId,templateCategory,templateType);
    }

    /**
     * 添加病历模板组
     * @param templateGroup 实体
     */
    @Transactional(rollbackFor = Exception.class)
    public void addGroup(TemplateGroup templateGroup) {
        validateGroup(templateGroup);
        templateGroup.setSortNum(getGroupSortNum(templateGroup.getClinicId(),templateGroup.getTemplateCategory(),templateGroup.getTemplateType(),templateGroup.getEmpId()));
        templateGroup.setIsDelete(YesOrNoEnum.NO.getValue());
        templateGroup.setIsEnabled(YesOrNoEnum.YES.getValue());
        templateGroup.setCreateTime(new Date());
        templateGroupMapper.insertSelective(templateGroup);
    }

    /**
     * 校验病历模板组实体
     * @param templateGroup 实体
     */
    public void validateGroup(TemplateGroup templateGroup) {
        templateGroup.setGroupName(StringUtil.removeAllWhitespace(templateGroup.getGroupName()));
        if (StringUtil.isBlank(templateGroup.getGroupName())) {
            throw new BusinessFailException("目录标题不能为空");
        }
        if(templateGroup.getGroupName().length() > Constants.TEMPLATE_GROUP_LENGTH){
            throw new BusinessFailException("目录标题"+Constants.TEMPLATE_GROUP_LENGTH+"个字以内！");
        }
        if(StringUtil.isBlank(templateGroup.getTemplateType())){
            templateGroup.setTemplateType(TemplateTypeEnum.PERSONAL.getValue());
        }
        if (StringUtil.isBlank(templateGroup.getTemplateType())) {
            throw new BusinessFailException("模板类型不能为空");
        }
        if(!TemplateTypeEnum.isValue(templateGroup.getTemplateType())){
            throw new BusinessFailException("模板类型非法");
        }
        if (StringUtil.isBlank(templateGroup.getTemplateCategory())) {
            throw new BusinessFailException("模板分类不能为空");
        }
        if(!TemplateCategoryEnum.isValue(templateGroup.getTemplateCategory())){
            throw new BusinessFailException("模板分类非法");
        }
    }

    /**
     * 获取组内排序号
     * @param clinicId
     * @param empId
     */
    public Integer getGroupSortNum(Long clinicId,String templateCategory,String templateType,Long empId){
        Integer maxSortNum = specTemplateMapper.getGroupMaxSortNum(clinicId,templateCategory,templateType,empId);
        if(StringUtil.isBlank(maxSortNum)){
            return CommonConstant.DEFAULT_1;
        }
        return maxSortNum + CommonConstant.DEFAULT_1;
    }

    /**
     * 移动分组
     */
    @Transactional(rollbackFor = Exception.class)
    public void moveGroupSort(MoveGroupRequest moveGroupRequest){
        TemplateGroup group = getGroupById(moveGroupRequest.getGroupId());
        if(group == null){
            throw new BusinessFailException("要移动的对象不存在");
        }
        if(StringUtil.isBlank(moveGroupRequest.getNextGroupId())){
            //代表移动到最下边
            group.setSortNum(getGroupSortNum(group.getClinicId(),group.getTemplateCategory(),group.getTemplateType(),group.getEmpId()));
        }else{
            TemplateGroup nextGroup = getGroupById(moveGroupRequest.getNextGroupId());
            if(nextGroup == null){
                throw new BusinessFailException("目标位置不存在");
            }
            //对目标位置之后的排序号+1
            specTemplateMapper.incrGroupSortNum(nextGroup.getClinicId(),group.getTemplateCategory(),nextGroup.getTemplateType(),nextGroup.getEmpId(),nextGroup.getSortNum());
            //修改要移动的对象的排序号为目标的位置的排序号
            group.setSortNum(nextGroup.getSortNum());
        }
        group.setUpdateUserId(moveGroupRequest.getUserId());
        group.setUpdateBy(moveGroupRequest.getUserBy());
        group.setUpdateTime(new Date());
        templateGroupMapper.updateByPrimaryKeySelective(group);
    }

    /**
     * 根据主键查询病历模板组信息
     * @param groupId 主键ID
     * @return 实体
     */
    public TemplateGroup getGroupById(Long groupId) {
        if (StringUtil.isBlank(groupId)) {
            return null;
        }
        TemplateGroup group = templateGroupMapper.selectByPrimaryKey(groupId);
        if (group == null || YesOrNoEnum.YES.getValue().equals(group.getIsDelete())) {
            return null;
        }
        return group;
    }

    /**
     * 修改病历模板组
     * @param templateGroup 实体
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateGroup(TemplateGroup templateGroup) {
        validateGroup(templateGroup);
        TemplateGroup dbTemplateGroup = getGroupById(templateGroup.getGroupId());
        if (dbTemplateGroup == null) {
            throw new BusinessFailException("模板组不存在");
        }
        if(!templateGroup.getEmpId().equals(dbTemplateGroup.getEmpId())){
            throw new BusinessFailException("暂无权限！");
        }
        dbTemplateGroup.setGroupName(templateGroup.getGroupName());
        dbTemplateGroup.setUpdateUserId(templateGroup.getUpdateUserId());
        dbTemplateGroup.setUpdateBy(templateGroup.getUpdateBy());
        dbTemplateGroup.setUpdateTime(new Date());
        templateGroupMapper.updateByPrimaryKeySelective(dbTemplateGroup);
    }

    /**
     * 删除病历模板组（逻辑删除）
     * @param group 实体
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteGroup(TemplateGroup group) {
        TemplateGroup dbGroup = getGroupById(group.getGroupId());
        if (dbGroup == null) {
            throw new BusinessFailException("模板组不存在");
        }
        if(TemplateTypeEnum.PERSONAL.getValue().equals(dbGroup.getTemplateType()) && !group.getEmpId().equals(dbGroup.getEmpId())){
            throw new BusinessFailException("暂无权限！");
        }
        Integer templateCount = specTemplateMapper.getTemplateCount(group.getClinicId(),dbGroup.getTemplateType(),dbGroup.getGroupId());
        if(templateCount > CommonConstant.DEFAULT_0){
            throw new BusinessFailException("目录内存在模板不能删除");
        }
        dbGroup.setIsDelete(YesOrNoEnum.YES.getValue());
        dbGroup.setUpdateUserId(group.getUpdateUserId());
        dbGroup.setUpdateBy(group.getUpdateBy());
        dbGroup.setUpdateTime(new Date());
        templateGroupMapper.updateByPrimaryKeySelective(dbGroup);
    }


    /**
     * 获取模板列表(用于刷新)
     * @param clinicId
     * @param empId
     * @param groupId
     * @return
     */
    public List<TemplateInfoVo> getTemplateList(Long clinicId,Long empId,Long groupId,String templateName) {
        TemplateGroup templateGroup = getGroupById(groupId);
        if(templateGroup == null){
            throw new BusinessFailException("模板组不存在");
        }
        return specTemplateMapper.getTemplateList(clinicId,empId,templateGroup.getTemplateType(),groupId,templateName);
    }


    /**
     * 获取模板类型是个人的模板的组内的最大的排序号
     * @param clinicId
     * @param groupId
     * @param empId
     * @return
     */
    public Integer getTemplateSortNum(Long clinicId, Long groupId, Long empId) {
        Integer maxSortNum = specTemplateMapper.getTemplateMaxSortNum(clinicId,groupId,empId);
        if(StringUtil.isBlank(maxSortNum)){
            return CommonConstant.DEFAULT_1;
        }
        return maxSortNum + CommonConstant.DEFAULT_1;
    }



    /**
     * 病历模板移动顺序
     * @param moveRequest
     */
    @Transactional(rollbackFor = Exception.class)
    public void moveTemplateSort(MoveTemplateSortRequest moveRequest) {
        if(StringUtil.isBlank(moveRequest.getTemplateType())){
            throw new BusinessFailException("模板类型不能为空");
        }
        if(!TemplateTypeEnum.isValue(moveRequest.getTemplateType())){
            throw new BusinessFailException("模板类型错误");
        }
        TemplateInfo templateInfo = getTemplateById(moveRequest.getTemplateId());
        if(templateInfo == null){
            throw new BusinessFailException("模板不存在");
        }
        if(TemplateTypeEnum.PERSONAL.getValue().equals(moveRequest.getTemplateType())){
            //个人目录操作 修改的是sort_num
            if(StringUtil.isBlank(moveRequest.getNextTemplateId())){
                //代表移动到最下边
                templateInfo.setSortNum(getTemplateSortNum(templateInfo.getClinicId(),templateInfo.getGroupId(),templateInfo.getEmpId()));
            }else{
                TemplateInfo nextTemplate = getTemplateById(moveRequest.getNextTemplateId());
                if(nextTemplate == null){
                    throw new BusinessFailException("目标位置不存在");
                }
                //对目标位置之后的排序号+1
                specTemplateMapper.incrTemplateSortNum(nextTemplate.getClinicId(),nextTemplate.getGroupId(),nextTemplate.getEmpId(),nextTemplate.getSortNum());
                //修改要移动的对象的排序号为目标的位置的排序号
                templateInfo.setSortNum(nextTemplate.getSortNum());
            }
        }else if (TemplateTypeEnum.SHARED.getValue().equals(moveRequest.getTemplateType())){
            //公共目录操作修改的是share_sort_num
            if(StringUtil.isBlank(moveRequest.getNextTemplateId())){
                //代表移动到最下边
                templateInfo.setShareSortNum(getTemplateShareSortNum(templateInfo.getClinicId(),templateInfo.getShareGroupId()));
            }else{
                TemplateInfo nextTemplate = getTemplateById(moveRequest.getNextTemplateId());
                if(nextTemplate == null){
                    throw new BusinessFailException("目标位置不存在");
                }
                //对目标位置之后的排序号+1
                specTemplateMapper.incrTemplateShareSortNum(nextTemplate.getClinicId(),nextTemplate.getShareGroupId(),nextTemplate.getShareSortNum());
                //修改要移动的对象的排序号为目标的位置的排序号
                templateInfo.setShareSortNum(nextTemplate.getShareSortNum());
            }
        }
        templateInfo.setUpdateUserId(moveRequest.getUserId());
        templateInfo.setUpdateBy(moveRequest.getUserBy());
        templateInfo.setUpdateTime(new Date());
        templateInfoMapper.updateByPrimaryKeySelective(templateInfo);
    }

    /**
     * 获取模板类型是公开的模板的组内的最大的排序号
     * @param clinicId
     * @param groupId
     * @return
     */
    public Integer getTemplateShareSortNum(Long clinicId, Long groupId) {
        Integer maxSortNum = specTemplateMapper.getTemplateShareSortNum(clinicId,groupId);
        if(StringUtil.isBlank(maxSortNum)){
            return CommonConstant.DEFAULT_1;
        }
        return maxSortNum + CommonConstant.DEFAULT_1;
    }


    /**
     * 根据主键获取病历模板信息
     * @param templateId 主键ID
     * @return 实体
     */
    public TemplateInfo getTemplateById(Long templateId) {
        if (StringUtil.isBlank(templateId)) {
            return null;
        }
        TemplateInfo templateMedical = templateInfoMapper.selectByPrimaryKey(templateId);
        if (templateMedical == null || YesOrNoEnum.YES.getValue().equals(templateMedical.getIsDelete())) {
            return null;
        }
        return templateMedical;
    }

    /**
     * 共享病历模板
     * @param template 实体
     */
    @Transactional(rollbackFor = Exception.class)
    public void shareTemplate(TemplateInfo template) {
        TemplateInfo dbTemplate = getTemplateById(template.getTemplateId());
        if (dbTemplate == null) {
            throw new BusinessFailException("模板不存在");
        }
        if(YesOrNoEnum.YES.getValue().equals(dbTemplate.getIsShare())){
            throw new BusinessFailException("模板已经是共享状态了！");
        }
        if(!template.getEmpId().equals(dbTemplate.getEmpId())){
            throw new BusinessFailException("暂无权限！");
        }
        TemplateGroup medicalGroup = getGroupById(template.getShareGroupId());
        if(medicalGroup == null){
            throw new BusinessFailException("要共享的组不存在");
        }
        if(!TemplateTypeEnum.SHARED.getValue().equals(medicalGroup.getTemplateType())){
            throw new BusinessFailException("只能共享到公开的组！");
        }
        if(YesOrNoEnum.YES.getValue().equals(dbTemplate.getIsShare())){
            return;
        }
        dbTemplate.setIsShare(YesOrNoEnum.YES.getValue());
        dbTemplate.setShareGroupId(template.getShareGroupId());
        //共享到组内最下边的位置
        dbTemplate.setShareSortNum(getTemplateShareSortNum(template.getClinicId(),template.getShareGroupId()));
        dbTemplate.setUpdateUserId(template.getUpdateUserId());
        dbTemplate.setUpdateBy(template.getUpdateBy());
        dbTemplate.setUpdateTime(new Date());
        templateInfoMapper.updateByPrimaryKeySelective(dbTemplate);
    }

    /**
     * 取消共享病历模板
     * @param template 实体
     */
    @Transactional(rollbackFor = Exception.class)
    public void unshareTemplate(TemplateInfo template) {
        TemplateInfo dbTemplate = getTemplateById(template.getTemplateId());
        if (dbTemplate == null) {
            throw new BusinessFailException("模板不存在");
        }
        if(YesOrNoEnum.NO.getValue().equals(dbTemplate.getIsShare())){
            throw new BusinessFailException("状态不允许");
        }
        if(!template.getEmpId().equals(dbTemplate.getEmpId())){
            throw new BusinessFailException("暂无权限！");
        }
        dbTemplate.setIsShare(YesOrNoEnum.NO.getValue());
        dbTemplate.setUpdateUserId(template.getUpdateUserId());
        dbTemplate.setUpdateBy(template.getUpdateBy());
        dbTemplate.setUpdateTime(new Date());
        templateInfoMapper.updateByPrimaryKeySelective(dbTemplate);
    }

    /**
     * 移动病历模板
     * @param moveTemplateRequest 实体
     */
    @Transactional(rollbackFor = Exception.class)
    public void moveTemplate(MoveTemplateRequest moveTemplateRequest) {
        if(StringUtil.isBlank(moveTemplateRequest.getTemplateType())){
            throw new BusinessFailException("模板类型不能为空");
        }
        if(!TemplateTypeEnum.isValue(moveTemplateRequest.getTemplateType())){
            throw new BusinessFailException("模板类型错误");
        }
        TemplateInfo dbTemplate = getTemplateById(moveTemplateRequest.getTemplateId());
        if (dbTemplate == null) {
            throw new BusinessFailException("模板不存在");
        }
        TemplateGroup moveGroup = getGroupById(moveTemplateRequest.getGroupId());
        if(moveGroup == null){
            throw new BusinessFailException("要移入的组不存在");
        }
        if(!moveGroup.getTemplateType().equals(moveTemplateRequest.getTemplateType())){
            throw new BusinessFailException("只能在当前目录下操作！");
        }
        if(TemplateTypeEnum.PERSONAL.getValue().equals(moveTemplateRequest.getTemplateType())){
            //个人的修改sortNum
            dbTemplate.setGroupId(moveGroup.getGroupId());
            dbTemplate.setSortNum(getTemplateSortNum(moveGroup.getClinicId(),moveGroup.getGroupId(),moveGroup.getEmpId()));
        }else {
            //公开的修改shareSortNum
            dbTemplate.setShareGroupId(moveGroup.getGroupId());
            dbTemplate.setShareSortNum(getTemplateShareSortNum(moveGroup.getClinicId(),moveGroup.getGroupId()));
        }
        dbTemplate.setUpdateUserId(moveTemplateRequest.getUserId());
        dbTemplate.setUpdateBy(moveTemplateRequest.getUserBy());
        dbTemplate.setUpdateTime(new Date());
        templateInfoMapper.updateByPrimaryKeySelective(dbTemplate);
    }

    /**
     * 复制病历模板到当前目录下
     * @param copyTemplateRequest 实体
     */
    @Transactional(rollbackFor = Exception.class)
    public void copyTemplate(CopyTemplateRequest copyTemplateRequest) {
        TemplateInfo templateInfo = getTemplateById(copyTemplateRequest.getTemplateId());
        if(templateInfo == null){
            throw new BusinessFailException("模板不存在");
        }
        if(!templateInfo.getEmpId().equals(copyTemplateRequest.getUserId())){
            throw new BusinessFailException("只支持复制自己的模板！");
        }
        TemplateGroup templateGroup = getGroupById(templateInfo.getGroupId());
        if(!TemplateTypeEnum.PERSONAL.getValue().equals(templateGroup.getTemplateType())){
            throw new BusinessFailException("只支持复制自己的模板！");
        }
        if(TemplateCategoryEnum.MEDICAL.getValue().equals(templateGroup.getTemplateCategory())){
            copyMedicalTemplate(copyTemplateRequest);
        }else if (TemplateCategoryEnum.EXAM.getValue().equals(templateGroup.getTemplateCategory())){
            copyExamTemplate(copyTemplateRequest);
        }else if (TemplateCategoryEnum.RX.getValue().equals(templateGroup.getTemplateCategory())){
            copyRxTemplate(copyTemplateRequest);
        }
    }


    /**
     * 复制病历模板
     * @param copyTemplateRequest
     */
    public void copyRxTemplate(CopyTemplateRequest copyTemplateRequest) {
        TemplateMedicalRxVo templateMedicalRxVo = getTemplateRxDetail(copyTemplateRequest.getClinicId(),copyTemplateRequest.getTemplateId());
        if(templateMedicalRxVo == null){
            throw new BusinessFailException("模板不存在");
        }
        templateMedicalRxVo.setTemplateName(templateMedicalRxVo.getTemplateName()+"_副本");
        doCopyRxTemplate(templateMedicalRxVo,copyTemplateRequest.getClinicId(),copyTemplateRequest.getUserId(),copyTemplateRequest.getUserBy());
    }

    /**
     * 执行复制处方的逻辑
     * @param templateMedicalRxVo
     * @param clinicId
     * @param userId
     * @param userBy
     */
    @Transactional(rollbackFor = Exception.class)
    public void doCopyRxTemplate(TemplateMedicalRxVo templateMedicalRxVo, Long clinicId, Long userId, String userBy) {
        //添加模板
        TemplateInfo templateInfo = new TemplateInfo();
        BeanUtils.copyProperties(templateMedicalRxVo,templateInfo);
        templateInfo.setEmpId(userId);
        templateInfo.setClinicId(clinicId);
        templateInfo.setCreateUserId(userId);
        templateInfo.setCreateBy(userBy);
        templateInsertSelective(templateInfo);
        //批量添加
        addTemplateMedicalRxsBatch(
                clinicId,
                templateInfo.getTemplateId(),
                userId,
                userBy,
                templateMedicalRxVo.getRxList()
        );

    }

    /**
     * 复制查验模板
     * @param copyTemplateRequest
     */
    @Transactional(rollbackFor = Exception.class)
    public void copyExamTemplate(CopyTemplateRequest copyTemplateRequest) {
        TemplateMedicalExamVo templateExamVo = getTemplateExamDetail(copyTemplateRequest.getClinicId(),copyTemplateRequest.getTemplateId());
        if(templateExamVo == null){
            throw new BusinessFailException("模板不存在");
        }
        templateExamVo.setTemplateName(templateExamVo.getTemplateName()+"_副本");
        doCopyExamTemplate(templateExamVo,copyTemplateRequest.getClinicId(),copyTemplateRequest.getUserId(),copyTemplateRequest.getUserBy());
    }

    /**
     * 执行复制的逻辑
     * @param templateExamVo
     * @param clinicId
     * @param userId
     * @param userBy
     */
    @Transactional(rollbackFor = Exception.class)
    public void doCopyExamTemplate(TemplateMedicalExamVo templateExamVo, Long clinicId, Long userId, String userBy) {
        //添加模板
        TemplateInfo templateInfo = new TemplateInfo();
        BeanUtils.copyProperties(templateExamVo,templateInfo);
        templateInfo.setEmpId(userId);
        templateInfo.setClinicId(clinicId);
        templateInfo.setCreateUserId(userId);
        templateInfo.setCreateBy(userBy);
        templateInsertSelective(templateInfo);
        //批量添加字段明细
        addExamDetailsBatch(
                clinicId,
                templateInfo.getTemplateId(),
                userId,
                userBy,
                templateExamVo.getDetailList());
    }

    /**
     * 复制处方模板
     * @param copyTemplateRequest
     */
    @Transactional(rollbackFor = Exception.class)
    public void copyMedicalTemplate(CopyTemplateRequest copyTemplateRequest) {
        TemplateMedicalFieldVo templateMedicalVo = getTemplateMedicalDetail(copyTemplateRequest.getClinicId(),copyTemplateRequest.getTemplateId());
        if(templateMedicalVo == null){
            throw new BusinessFailException("模板不存在");
        }
        templateMedicalVo.setTemplateName(templateMedicalVo.getTemplateName()+"_副本");
        doCopyMedicalTemplate(templateMedicalVo,copyTemplateRequest.getClinicId(),copyTemplateRequest.getUserId(),copyTemplateRequest.getUserBy());
    }

    /**
     * 执行复制的逻辑
     * @param templateMedicalVo
     * @param clinicId
     * @param userId
     * @param userBy
     */
    @Transactional(rollbackFor = Exception.class)
    public void doCopyMedicalTemplate(TemplateMedicalFieldVo templateMedicalVo,Long clinicId,Long userId,String userBy) {
        //复制模板
        TemplateInfo templateInfo = new TemplateInfo();
        BeanUtils.copyProperties(templateMedicalVo,templateInfo);
        templateInfo.setEmpId(userId);
        templateInfo.setClinicId(clinicId);
        templateInfo.setCreateUserId(userId);
        templateInfo.setCreateBy(userBy);
        templateInsertSelective(templateInfo);
        //复制字段
        TemplateMedicalField templateMedicalField = new TemplateMedicalField();
        templateMedicalField.setTemplateId(templateInfo.getTemplateId());
        templateMedicalField.setFieldListJson(templateMedicalVo.getFieldListJson());
        templateMedicalField.setClinicId(clinicId);
        templateMedicalField.setCreateUserId(userId);
        templateMedicalField.setCreateBy(userBy);
        medicalFieldInsertSelective(templateMedicalField);
    }

    /**
     * 拉取模板到个人目录
     * @param fetchTemplateRequest 实体
     */
    @Transactional(rollbackFor = Exception.class)
    public void fetchTemplate(FetchTemplateRequest fetchTemplateRequest) {
        TemplateInfo templateInfo = getTemplateById(fetchTemplateRequest.getTemplateId());
        if(templateInfo == null){
            throw new BusinessFailException("模板不存在");
        }
        if(YesOrNoEnum.NO.getValue().equals(templateInfo.getIsShare())){
            throw new BusinessFailException("状态不允许！");
        }
        TemplateGroup targetGroup = getGroupById(fetchTemplateRequest.getGroupId());
        if(targetGroup == null){
            throw new BusinessFailException("目的目录不存在");
        }
        //如果目录不是自己的或者目录不是个人的
        if(!targetGroup.getEmpId().equals(fetchTemplateRequest.getUserId())
                || !TemplateTypeEnum.PERSONAL.getValue().equals(targetGroup.getTemplateType())){
            throw new BusinessFailException("只能拉取到个人的目录！");
        }
        if(TemplateCategoryEnum.MEDICAL.getValue().equals(targetGroup.getTemplateCategory())){
            fetchMedicalTemplate(fetchTemplateRequest);
        }else if (TemplateCategoryEnum.EXAM.getValue().equals(targetGroup.getTemplateCategory())){
            fetchExamTemplate(fetchTemplateRequest);
        }else if (TemplateCategoryEnum.RX.getValue().equals(targetGroup.getTemplateCategory())){
            fetchRxTemplate(fetchTemplateRequest);
        }
    }

    /**
     * 拉取处方模板
     * @param fetchTemplateRequest
     */
    public void fetchRxTemplate(FetchTemplateRequest fetchTemplateRequest) {
        TemplateMedicalRxVo templateRxDetail = getTemplateRxDetail(fetchTemplateRequest.getClinicId(),fetchTemplateRequest.getTemplateId());
        if(templateRxDetail == null){
            throw new BusinessFailException("模板不存在");
        }
        templateRxDetail.setGroupId(fetchTemplateRequest.getGroupId());
        templateRxDetail.setTemplateName(templateRxDetail.getTemplateName()+"_个人版");
        doCopyRxTemplate(templateRxDetail,fetchTemplateRequest.getClinicId(),fetchTemplateRequest.getUserId(),fetchTemplateRequest.getUserBy());
    }

    /**
     * 拉取查验模板
     * @param fetchTemplateRequest
     */
    public void fetchExamTemplate(FetchTemplateRequest fetchTemplateRequest) {
        TemplateMedicalExamVo templateExamVo = getTemplateExamDetail(fetchTemplateRequest.getClinicId(),fetchTemplateRequest.getTemplateId());
        if(templateExamVo == null){
            throw new BusinessFailException("模板不存在");
        }
        templateExamVo.setGroupId(fetchTemplateRequest.getGroupId());
        templateExamVo.setTemplateName(templateExamVo.getTemplateName()+"_个人版");
        doCopyExamTemplate(templateExamVo,fetchTemplateRequest.getClinicId(),fetchTemplateRequest.getUserId(),fetchTemplateRequest.getUserBy());
    }

    /**
     * 拉取病历模板
     * @param fetchTemplateRequest
     */
    public void fetchMedicalTemplate(FetchTemplateRequest fetchTemplateRequest) {
        TemplateMedicalFieldVo templateMedicalVo = getTemplateMedicalDetail(fetchTemplateRequest.getClinicId(),fetchTemplateRequest.getTemplateId());
        if(templateMedicalVo == null){
            throw new BusinessFailException("模板不存在");
        }
        templateMedicalVo.setGroupId(fetchTemplateRequest.getGroupId());
        templateMedicalVo.setTemplateName(templateMedicalVo.getTemplateName()+"_个人版");
        doCopyMedicalTemplate(templateMedicalVo,fetchTemplateRequest.getClinicId(),fetchTemplateRequest.getUserId(),fetchTemplateRequest.getUserBy());
    }

    /**
     * 删除病历模板（逻辑删除）
     * @param templateMedical 实体
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteTemplate(TemplateInfo templateMedical) {
        TemplateInfo dbTemplate = getTemplateById(templateMedical.getTemplateId());
        if (dbTemplate == null) {
            throw new BusinessFailException("模板不存在");
        }
        dbTemplate.setIsDelete(YesOrNoEnum.YES.getValue());
        dbTemplate.setUpdateUserId(templateMedical.getUpdateUserId());
        dbTemplate.setUpdateBy(templateMedical.getUpdateBy());
        dbTemplate.setUpdateTime(new Date());
        templateInfoMapper.updateByPrimaryKeySelective(dbTemplate);
    }


    /**
     * 获取病历模板详情
     * @param clinicId
     * @param templateId
     * @return
     */
    public TemplateMedicalFieldVo getTemplateMedicalDetail(Long clinicId, Long templateId){
        if(StringUtil.isBlank(templateId)){
            throw new BusinessFailException("模板不存在");
        }
        TemplateMedicalFieldVo templateMedicalFieldVo = specTemplateMapper.getTemplateMedicalFieldDetail(clinicId,templateId);
        if(templateMedicalFieldVo == null){
            throw new BusinessFailException("模板不存在");
        }
        //获取病历字段
        List<MedicalFieldDetail> fieldList = JsonUtil.json2Obj(templateMedicalFieldVo.getFieldListJson(),
                new TypeReference<List<MedicalFieldDetail>>() {});
        if(!CollectionUtils.isEmpty(fieldList)){
            fieldList.sort(Comparator.comparingInt(MedicalFieldDetail::getSortNum));
            templateMedicalFieldVo.setFieldList(fieldList);
        }
        return templateMedicalFieldVo;
    }


    /**
     * 添加模板
     * @param template
     */
    @Transactional(rollbackFor = Exception.class)
    public void addTemplate(TemplateInfo template) {
        //参数校验
        validateTemplate(template, OperateTypeEnum.ADD.getValue());
        //添加模板
        templateInsertSelective(template);
    }

    /**
     * 添加病历模板
     * @param templateMedicalFieldDTO
     */
    @Transactional(rollbackFor = Exception.class)
    public void addTemplateMedicalDTO(TemplateMedicalFieldDTO templateMedicalFieldDTO){
        //参数校验
        validateTemplateMedicalDTO(templateMedicalFieldDTO,OperateTypeEnum.ADD.getValue());
        templateInsertSelective(templateMedicalFieldDTO);
        //批量添加字段明细
        addFieldDetailList(
                templateMedicalFieldDTO.getClinicId(),
                templateMedicalFieldDTO.getTemplateId(),
                templateMedicalFieldDTO.getCreateUserId(),
                templateMedicalFieldDTO.getCreateBy(),
                templateMedicalFieldDTO.getDoctorAdvice(),
                templateMedicalFieldDTO.getFieldList());
    }

    /**
     * 新增的模板
     * @param templateInfo
     */
    @Transactional(rollbackFor = Exception.class)
    public void templateInsertSelective(TemplateInfo templateInfo){
        //新增的模板默认不共享
        templateInfo.setIsShare(YesOrNoEnum.NO.getValue());
        templateInfo.setSortNum(getTemplateSortNum(templateInfo.getClinicId(),templateInfo.getGroupId(),templateInfo.getEmpId()));
        templateInfo.setIsDelete(YesOrNoEnum.NO.getValue());
        templateInfo.setIsEnabled(YesOrNoEnum.YES.getValue());
        templateInfo.setCreateTime(new Date());
        templateInfoMapper.insertSelective(templateInfo);
    }

    /**
     * 保存病历模板字段详情
     * @param clinicId
     * @param templateId
     * @param createUserId
     * @param createBy
     * @param detailList
     */
    @Transactional(rollbackFor = Exception.class)
    public void addFieldDetailList(Long clinicId, Long templateId, Long createUserId, String createBy, String doctorAdvice,List<MedicalFieldDetail> detailList) {
        TemplateMedicalField templateMedicalField = new TemplateMedicalField();
        templateMedicalField.setTemplateId(templateId);
        templateMedicalField.setDoctorAdvice(doctorAdvice);
        templateMedicalField.setFieldListJson(JsonUtil.obj2Json(detailList));
        templateMedicalField.setClinicId(clinicId);
        templateMedicalField.setCreateUserId(createUserId);
        templateMedicalField.setCreateBy(createBy);
        medicalFieldInsertSelective(templateMedicalField);
    }

    /**
     * 保存模板病历字段
     * @param templateMedicalField
     */
    @Transactional(rollbackFor = Exception.class)
    public void medicalFieldInsertSelective(TemplateMedicalField templateMedicalField){
        templateMedicalField.setIsEnabled(YesOrNoEnum.YES.getValue());
        templateMedicalField.setIsDelete(YesOrNoEnum.NO.getValue());
        templateMedicalField.setCreateTime(new Date());
        templateMedicalFieldMapper.insertSelective(templateMedicalField);
    }

    /**
     * 修改模板
     * @param templateMedicalFieldDTO
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateTemplateMedicalDTO(TemplateMedicalFieldDTO templateMedicalFieldDTO){
        //参数校验
        validateTemplateMedicalDTO(templateMedicalFieldDTO,OperateTypeEnum.EDIT.getValue());
        TemplateInfo dbTemplateMedical = getTemplateById(templateMedicalFieldDTO.getTemplateId());
        if(dbTemplateMedical == null){
            throw new BusinessFailException("模板不存在");
        }
        if(!templateMedicalFieldDTO.getEmpId().equals(dbTemplateMedical.getEmpId())){
            throw new BusinessFailException("暂无权限！");
        }
        templateMedicalFieldDTO.setUpdateTime(new Date());
        templateInfoMapper.updateByPrimaryKeySelective(templateMedicalFieldDTO);
        //批量添加字段明细
        saveOrUpdateFieldDetailList(
                templateMedicalFieldDTO.getClinicId(),
                templateMedicalFieldDTO.getTemplateId(),
                templateMedicalFieldDTO.getUpdateUserId(),
                templateMedicalFieldDTO.getUpdateBy(),
                templateMedicalFieldDTO.getDoctorAdvice(),
                templateMedicalFieldDTO.getFieldList());
    }

    /**
     * 修改病历字段
     * @param templateId
     * @param updateUserId
     * @param updateBy
     * @param detailList
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveOrUpdateFieldDetailList(Long clinicId,Long templateId, Long updateUserId, String updateBy, String doctorAdvice,List<MedicalFieldDetail> detailList) {
        TemplateMedicalField templateMedicalField = getTemplateMedicalFieldById(templateId);
        if(templateMedicalField == null){
            addFieldDetailList(clinicId, templateId, updateUserId, updateBy, doctorAdvice, detailList);
        }else {
            updateFieldDetailList(templateId,updateUserId,updateBy,doctorAdvice,detailList);
        }
    }

    /**
     * 修改病历字段
     * @param templateId
     * @param updateUserId
     * @param updateBy
     * @param detailList
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateFieldDetailList(Long templateId, Long updateUserId, String updateBy, String doctorAdvice,List<MedicalFieldDetail> detailList) {
        TemplateMedicalField templateMedicalField = new TemplateMedicalField();
        templateMedicalField.setTemplateId(templateId);
        templateMedicalField.setDoctorAdvice(doctorAdvice);
        templateMedicalField.setFieldListJson(JsonUtil.obj2Json(detailList));
        templateMedicalField.setUpdateUserId(updateUserId);
        templateMedicalField.setUpdateBy(updateBy);
        templateMedicalField.setUpdateTime(new Date());
        templateMedicalFieldMapper.updateByPrimaryKeySelective(templateMedicalField);
    }

    /**
     * 根据模板ID查询病历字段详情
     * @param templateId
     * @return
     */
    public TemplateMedicalField getTemplateMedicalFieldById(Long templateId){
        if(StringUtil.isBlank(templateId)){
            return null;
        }
        TemplateMedicalField templateMedicalField = templateMedicalFieldMapper.selectByPrimaryKey(templateId);
        if(templateMedicalField == null || YesOrNoEnum.YES.getValue().equals(templateMedicalField.getIsDelete())){
            return null;
        }
        return templateMedicalField;
    }


    /**
     * 校验病历模板
     * @param templateMedicalFieldDTO
     * @param operateType
     */
    public void validateTemplateMedicalDTO(TemplateMedicalFieldDTO templateMedicalFieldDTO,String operateType) {
        //验证模板信息
        validateTemplate(templateMedicalFieldDTO,operateType);
        //验证病历字段
        validateMedicalField(YesOrNoEnum.NO.getValue(),operateType,templateMedicalFieldDTO.getFieldList());
    }

    public void validateTemplate(TemplateInfo templateInfo,String operateType) {
        templateInfo.setTemplateName(StringUtil.removeAllWhitespace(templateInfo.getTemplateName()));
        if (StringUtil.isBlank(templateInfo.getTemplateName())) {
            throw new BusinessFailException("模板名称不能为空");
        }
        if (templateInfo.getTemplateName().length() > Constants.TEMPLATE_LENGTH) {
            throw new BusinessFailException("模板名称最多"+Constants.TEMPLATE_LENGTH+"个字以内！");
        }
        templateInfo.setRecomScene(StringUtil.removeAllWhitespace(templateInfo.getRecomScene()));
        if(StringUtil.isNotBlank(templateInfo.getRecomScene())){
            if(!TagCheckUtil.isValidTags(templateInfo.getRecomScene(),CommonConstant.DEFAULT_3,CommonConstant.DEFAULT_5)){
                throw new BusinessFailException("推荐场景验证失败：最多"+CommonConstant.DEFAULT_3+"个，并且每个场景不超过"+CommonConstant.DEFAULT_5+"个字");
            }
        }
        if(OperateTypeEnum.ADD.getValue().equals(operateType)){
            TemplateGroup templateGroup = getGroupById(templateInfo.getGroupId());
            if(templateGroup == null){
                throw new BusinessFailException("目录不存在");
            }
        }
    }



    /**
     * 获取模板详情
     * @param clinicId
     * @param templateId
     * @return
     */
    public TemplateMedicalExamVo getTemplateExamDetail(Long clinicId, Long templateId){
        if(StringUtil.isBlank(templateId)){
            throw new BusinessFailException("模板不存在");
        }
        TemplateMedicalExamVo templateExamVo = specTemplateMapper.getTemplateExamDetail(clinicId,templateId);
        return templateExamVo;
    }

    /**
     * 添加查验模板
     * @param templateMedicalExamDTO
     */
    @Transactional(rollbackFor = Exception.class)
    public void addTemplateExamDTO(TemplateMedicalExamDTO templateMedicalExamDTO){
        //参数校验
        validateTemplateExamDTO(templateMedicalExamDTO,OperateTypeEnum.ADD.getValue());
        //添加模板
        templateInsertSelective(templateMedicalExamDTO);
        //批量添加字段明细
        addExamDetailsBatch(
                templateMedicalExamDTO.getClinicId(),
                templateMedicalExamDTO.getTemplateId(),
                templateMedicalExamDTO.getCreateUserId(),
                templateMedicalExamDTO.getCreateBy(),
                templateMedicalExamDTO.getExamList());
    }

    /**
     * 修改模板
     * @param templateMedicalExamDTO
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateTemplateExamDTO(TemplateMedicalExamDTO templateMedicalExamDTO){
        //参数校验
        validateTemplateExamDTO(templateMedicalExamDTO,OperateTypeEnum.EDIT.getValue());
        TemplateInfo dbTemplateExam = getTemplateById(templateMedicalExamDTO.getTemplateId());
        if(dbTemplateExam == null){
            throw new BusinessFailException("模板不存在");
        }
        if(!templateMedicalExamDTO.getEmpId().equals(dbTemplateExam.getEmpId())){
            throw new BusinessFailException("暂无权限");
        }
        templateMedicalExamDTO.setUpdateTime(new Date());
        templateInfoMapper.updateByPrimaryKeySelective(templateMedicalExamDTO);
        //批量添加字段明细
        updateExamDetailsBatch(
                templateMedicalExamDTO.getClinicId(),
                templateMedicalExamDTO.getTemplateId(),
                templateMedicalExamDTO.getUpdateUserId(),
                templateMedicalExamDTO.getUpdateBy(),
                templateMedicalExamDTO.getExamList());
    }

    /**
     * 批量添加字段
     * @param templateId
     * @param detailList
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateExamDetailsBatch(Long clinicId,
                                       Long templateId,
                                       Long updateUserId,String updateBy,
                                       List<ExamDetail> detailList) {
        //先批量删除旧的
        deleteExamDetailsBatch(templateId,updateUserId,updateBy);
        //批量添加
        addExamDetailsBatch(clinicId,templateId,updateUserId,updateBy,detailList);
    }

    /**
     * 删除病历字段
     * @param templateId
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteExamDetailsBatch(Long templateId,Long updateUserId,String updateBy){
        TemplateMedicalExamExample example = new TemplateMedicalExamExample();
        TemplateMedicalExamExample.Criteria criteria = example.createCriteria();
        criteria.andTemplateIdEqualTo(templateId);
        criteria.andIsDeleteEqualTo(YesOrNoEnum.NO.getValue());
        TemplateMedicalExam templateMedicalExam = new TemplateMedicalExam();
        templateMedicalExam.setIsDelete(YesOrNoEnum.YES.getValue());
        templateMedicalExam.setUpdateUserId(updateUserId);
        templateMedicalExam.setUpdateBy(updateBy);
        templateMedicalExam.setUpdateTime(new Date());
        templateMedicalExamMapper.updateByExampleSelective(templateMedicalExam,example);
    }

    /**
     * 批量添加
     * @param clinicId
     * @param templateId
     * @param createUserId
     * @param createBy
     * @param detailList
     */
    @Transactional(rollbackFor = Exception.class)
    public void addExamDetailsBatch(Long clinicId, Long templateId, Long createUserId, String createBy, List<ExamDetail> detailList) {
        if(CollectionUtils.isEmpty(detailList)){
            return;
        }
        Date createTime = new Date();
        List<TemplateMedicalExam> examList = new ArrayList<>();
        for(ExamDetail examDetail : detailList){
            TemplateMedicalExam templateMedicalExam = new TemplateMedicalExam();
            BeanUtils.copyProperties(examDetail,templateMedicalExam);
            templateMedicalExam.setTemplateId(templateId);
            templateMedicalExam.setClinicId(clinicId);
            templateMedicalExam.setIsEnabled(YesOrNoEnum.YES.getValue());
            templateMedicalExam.setIsDelete(YesOrNoEnum.NO.getValue());
            templateMedicalExam.setCreateUserId(createUserId);
            templateMedicalExam.setCreateBy(createBy);
            templateMedicalExam.setCreateTime(createTime);
            examList.add(templateMedicalExam);
        }
        specTemplateMapper.addMedicalExamBatch(examList);
    }


    /**
     * 校验查验模板
     * @param templateExamDTO
     */
    public void validateTemplateExamDTO(TemplateMedicalExamDTO templateExamDTO,String operateType) {
        //模板信息校验
        validateTemplate(templateExamDTO,operateType);
        //项目信息校验
        validateMedicalExam(YesOrNoEnum.NO.getValue(),templateExamDTO.getExamList());
    }



    /**
     * 获取模板详情
     * @param clinicId
     * @param templateId
     * @return
     */
    public TemplateMedicalRxVo getTemplateRxDetail(Long clinicId, Long templateId){
        if(StringUtil.isBlank(templateId)){
            throw new BusinessFailException("模板不存在");
        }
        TemplateMedicalRxVo templateMedicalRxVo = specTemplateMapper.getTemplateRxDetail(clinicId,templateId);
        if(templateMedicalRxVo == null){
            throw new BusinessFailException("模板不存在");
        }
        templateMedicalRxVo.setRxList(handleRxList(templateMedicalRxVo.getRxList()));
        /**
         * 模板需要计算价格，因为处方在选取模板的时候要用
         */
        handleRxPrice(clinicId,templateMedicalRxVo.getRxList());
        return templateMedicalRxVo;
    }

    /**
     * 添加处方模板
     * @param templateMedicalRxDTO
     */
    @Transactional(rollbackFor = Exception.class)
    public void addTemplateRxDTO(TemplateMedicalRxDTO templateMedicalRxDTO){
        validateTemplateDTO(templateMedicalRxDTO,OperateTypeEnum.ADD.getValue());
        //保存模板
        templateInsertSelective(templateMedicalRxDTO);
        //批量添加
        addTemplateMedicalRxsBatch(
                templateMedicalRxDTO.getClinicId(),
                templateMedicalRxDTO.getTemplateId(),
                templateMedicalRxDTO.getCreateUserId(),
                templateMedicalRxDTO.getCreateBy(),
                templateMedicalRxDTO.getRxList()
        );
    }

    /**
     * 批量添加处方
     * @param clinicId
     * @param templateId
     * @param createUserId
     * @param createBy
     * @param rxList
     */
    @Transactional(rollbackFor = Exception.class)
    public void addTemplateMedicalRxsBatch(Long clinicId, Long templateId, Long createUserId, String createBy, List<RxBase> rxList) {
        if(CollectionUtils.isEmpty(rxList)){
            return;
        }
        Date createTime = new Date();
        List<TemplateMedicalRx> templateMedicalRxList = new ArrayList<>();
        for (RxBase rxBase : rxList) {
            TemplateMedicalRx templateMedicalRx = new TemplateMedicalRx();
            BeanUtils.copyProperties(rxBase,templateMedicalRx);
            templateMedicalRx.setTemplateId(templateId);
            templateMedicalRx.setClinicId(clinicId);
            templateMedicalRx.setIsEnabled(YesOrNoEnum.YES.getValue());
            templateMedicalRx.setIsDelete(YesOrNoEnum.NO.getValue());
            templateMedicalRx.setCreateUserId(createUserId);
            templateMedicalRx.setCreateBy(createBy);
            templateMedicalRx.setCreateTime(createTime);
            if(StringUtil.isBlank(templateMedicalRx.getRxJson())){
                // 根据 rxType 类型添加到对应的列表中
                if (RxTypeEnum.DRUG.getValue().equals(rxBase.getRxType())) {
                    RxDrug rxDrug = (RxDrug) rxBase;
                    templateMedicalRx.setRxJson(JsonUtil.obj2Json(rxDrug.getDetailList()));
                } else if (RxTypeEnum.INFUSION.getValue().equals(rxBase.getRxType())) {
                    RxInfusion rxInfusion = (RxInfusion) rxBase;
                    templateMedicalRx.setRxJson(JsonUtil.obj2Json(rxInfusion.getGroupList()));
                } else if (RxTypeEnum.EXT.getValue().equals(rxBase.getRxType())) {
                    RxExt rxExt = (RxExt) rxBase;
                    templateMedicalRx.setRxJson(JsonUtil.obj2Json(rxExt.getExtInfo()));
                } else if (RxTypeEnum.TCM.getValue().equals(rxBase.getRxType())) {
                    RxTcm rxTcm = (RxTcm) rxBase;
                    templateMedicalRx.setRxJson(JsonUtil.obj2Json(rxTcm.getTcmInfo()));
                }
            }
            templateMedicalRxList.add(templateMedicalRx);
        }
        specTemplateMapper.addMedicalRxBatch(templateMedicalRxList);
    }


    /**
     * 校验处方模板
     * @param templateMedicalRxDTO
     * @param operateType
     */
    public void validateTemplateDTO(TemplateMedicalRxDTO templateMedicalRxDTO,String operateType) {
        //验证模板信息
        validateTemplate(templateMedicalRxDTO,operateType);
        //验证处方信息
        validateMedicalRx(YesOrNoEnum.NO.getValue(),templateMedicalRxDTO.getClinicId(),templateMedicalRxDTO.getRxList());
    }


    /**
     * 修改模板
     * @param templateMedicalRxDTO
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateTemplateRxDTO(TemplateMedicalRxDTO templateMedicalRxDTO){
        //参数校验
        validateTemplateDTO(templateMedicalRxDTO,OperateTypeEnum.EDIT.getValue());
        TemplateInfo templateRx = getTemplateById(templateMedicalRxDTO.getTemplateId());
        if(templateRx == null){
            throw new BusinessFailException("模板不存在");
        }
        templateMedicalRxDTO.setUpdateTime(new Date());
        templateInfoMapper.updateByPrimaryKeySelective(templateMedicalRxDTO);
        updateMedicalRxList(
                templateMedicalRxDTO.getClinicId(),
                templateMedicalRxDTO.getTemplateId(),
                templateMedicalRxDTO.getUpdateUserId(),
                templateMedicalRxDTO.getUpdateBy(),
                templateMedicalRxDTO.getRxList()
        );
    }

    /**
     * 批量修改处方
     * @param clinicId
     * @param templateId
     * @param updateUserId
     * @param updateBy
     * @param rxList
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateMedicalRxList(Long clinicId,Long templateId, Long updateUserId, String updateBy, List<RxBase> rxList) {
        //先删除
        delTemplateMedicalRxsBatch(templateId,updateUserId,updateBy);
        //在添加
        addTemplateMedicalRxsBatch(clinicId,templateId,updateUserId,updateBy,rxList);
    }


    /**
     * 先删除
     * @param templateId
     * @param updateUserId
     * @param updateBy
     */
    @Transactional(rollbackFor = Exception.class)
    public void delTemplateMedicalRxsBatch(Long templateId, Long updateUserId, String updateBy) {
        TemplateMedicalRxExample example = new TemplateMedicalRxExample();
        TemplateMedicalRxExample.Criteria criteria = example.createCriteria();
        criteria.andTemplateIdEqualTo(templateId);
        criteria.andIsDeleteEqualTo(YesOrNoEnum.NO.getValue());
        TemplateMedicalRx templateMedicalRx = new TemplateMedicalRx();
        templateMedicalRx.setIsDelete(YesOrNoEnum.YES.getValue());
        templateMedicalRx.setUpdateUserId(updateUserId);
        templateMedicalRx.setUpdateBy(updateBy);
        templateMedicalRx.setUpdateTime(new Date());
        templateMedicalRxMapper.updateByExampleSelective(templateMedicalRx,example);
    }

}
